package com.flow.framework.core.system.helper;

import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.core.constant.FrameworkCoreConstant;
import com.flow.framework.core.service.properties.ISystemConfigPropertiesService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 微服务工作节点工具类
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/23
 */
@Slf4j
@RequiredArgsConstructor
public class ServiceWorkerHelper {

    private final ISystemConfigPropertiesService systemConfigPropertiesService;

    /**
     * 获取数据中心ID
     *
     * @return 数据中心id
     */
    public long getDateCenterId() {
        return getDataCenterOrWorkerId(FrameworkCoreConstant.DATA_CENTER_ID_KEY, FrameworkCoreConstant.DATA_CENTER_ID_MAX_VALUE);
    }

    /**
     * 获取节点ID
     *
     * @return 工作节点id
     */
    public long getWorkerId() {
        return getDataCenterOrWorkerId(FrameworkCoreConstant.WORKER_ID_KEY, FrameworkCoreConstant.WORKER_ID_MAX_VALUE);
    }

    private long getDataCenterOrWorkerId(String configKey, long maxValue) {
        String idStr = systemConfigPropertiesService.getConfigValue(configKey);
        if (VerifyUtil.isEmpty(idStr)) {
            log.error("data center id or worker id is empty. config key : {}", configKey);
            throw new CheckedException(SystemErrorCode.PARAMS_ERROR);
        }

        try {
            long id = Long.parseLong(idStr);
            if (id < 0 || id > maxValue) {
                log.error("data center id or worker id error. config key : {}", configKey);
                throw new CheckedException(SystemErrorCode.PARAMS_ERROR);
            }
            return id;
        } catch (Exception e) {
            log.error("data center id or worker id error. config key : {}", configKey, e);
            throw new CheckedException(SystemErrorCode.PARAMS_ERROR, "data center id or worker id error.", e);
        }
    }
}